using Magiq.Delete;

namespace Magiq.Databases.Delete
{
    public class DatabaseDeleteStrategy<T> : IDeleteStrategy,
                                             IDatabaseBasedExecution where T : class
    {
        private readonly IDelete<T> delete;

        public DatabaseDeleteStrategy(IOrmAdapter ormAdapter, IDelete<T> delete)
        {
            OrmAdapter = ormAdapter;
            this.delete = delete;
        }

        #region IDatabaseBasedExecution Members

        public IOrmAdapter OrmAdapter { get; private set; }

        #endregion

        #region IDeleteStrategy Members

        public int Execute()
        {
            var databaseDeletes = OrmAdapter.BuildDatabaseDeletes(delete);
            var result = 0;
            foreach (var databaseDelete in databaseDeletes)
            {
                var builder = new DeleteCommandBuilder<T>(OrmAdapter,databaseDelete.Source);
                var command = builder.GetCommand();
                result += command.ExecuteNonQuerySafe();
            }
            return result;
        }

        #endregion
    }
}